#!/usr/bin/env python

#################################################################################
#
# Copyright (c) 2006 Michigan State University
#
# This program is free software; you can redistribute it and/or
# modify it under the terms of the GNU General Public License
# as published by the Free Software Foundation; either version 2
# of the License, or (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
#################################################################################

#################################################################################
#
#	Author:
#		Nathan Collins <npcollins@gmail.com>
#
#################################################################################

import random, string
from oaicookie import *
from dbinter import *
from util import *
import cgi, os


def authenticate():
	"""
	Authenticate login; verify versus the database.
	"""
	params = cgi.FieldStorage()
	db = oai_db()
	db.connect()
	#######################################################
	# check cookie for active session
	sidCookie = getCookieVar('sid')
	try:
		if sidCookie == '': raise

		# session ID found, attempt to verify
		info = db.query_dict("SELECT * FROM directoryLogins WHERE sessionID = '%s';" % sidCookie)
		if len(info) < 1: raise

		info = info[0]

		# verify address
		rip = cgi.escape(os.environ["REMOTE_ADDR"])
		if info['lastAddress'] != rip: return 0, 'Session failed.'

		# check for session timeout
		expireLimit = 60 * 60 * 2	# sec * min * hour
		lastLogin = str(info['lastLogin'])
		expire = db.query_dict("SELECT TIME_TO_SEC(TIMEDIFF( NOW(), TIMESTAMP('%s') )) as diff;" % lastLogin)
		expire = expire[0]

		if expire['diff'] > expireLimit: return 0, 'Session timeout.'

		# session resumed
		querystr = "UPDATE directoryLogins SET lastLogin = CURRENT_TIMESTAMP WHERE loginName = %s;"
		db.query_args(querystr, (info['loginName'],) )
		return 1, 'Logged out.'  # this message appears when you are logging out

	except: pass

	#######################################################
	# check to see if login info was passed
	try:
		user = cui(params['u'].value)
		passwd = cui(params['p'].value)
		salt = cui(params['s'].value)
	except: 
		# first login attempt
		db.disconnect()
		return 0,'Login below.'

	try:
		# ok, we have an attempt to login
		info = db.query_dict("SELECT * FROM directoryLogins WHERE loginName = '%s';" % user)
		if len(info) < 1: raise
		info = info[0]
		
		serverpw = make_hash(salt + info['loginPassword'])

		# verify pw and that account is active
		if serverpw != passwd or info['enableAccount'] == 'N': raise
		
		# login ok, generate session id
		sid = make_hash(info['loginName'] + genRandStr())
		# remote ip
		rip = cgi.escape(os.environ["REMOTE_ADDR"])

		# set sid in cookie
		setCookieVars( {'sid':sid} )

		# update the database
		data = (rip,sid,info['loginName'])
		querystr = "UPDATE directoryLogins SET lastLogin = CURRENT_TIMESTAMP, lastAddress = %s, sessionID = %s WHERE loginName = %s;"
		db.query_args(querystr,data)
		
		db.disconnect()

		# login successful
		return 1, 'Logged Out.'		# this message shouldn't be displayed

	except: pass

	#############################################
	# if neither, then failed authenticate
	db.disconnect()
	return 0, 'Login Failed.'


# eof

